<template>
	<view class="container">
		<view style="height: 50rpx;"></view>
		<!-- 当前房间与状态 -->
		<view class="room-header">
			<view class="room-info">
				<view class="room-name">{{currentRoom.name || '选择房间'}}</view>
				<view class="room-status" :class="{'status-live': isLive}">
					<text class="status-dot"></text>
					<text class="status-text">{{isLive ? '直播中' : '离线'}}</text>
				</view>
			</view>
			<view class="room-switch-btn" @click="showRoomSelector">
				<text class="switch-text">切换</text>
				<text class="switch-icon">▼</text>
			</view>
		</view>

		<!-- 功能操作区域 -->
		<view class="function-section">
			<view class="section-title">
				<text class="title-text">功能操作</text>
				<text class="title-desc">在这里进行播放配置和音频管理</text>
			</view>
			
			<view class="function-grid">
				<view class="function-card" @click="configurePlaylist">
					<view class="card-icon-wrapper primary">
						<text class="card-icon-large">⚙️</text>
					</view>
					<view class="card-info">
						<text class="card-title">播放配置</text>
						<text class="card-desc">配置播放列表和规则</text>
					</view>
					<text class="card-arrow">→</text>
				</view>
				
				<view class="function-card" @click="manageAudio">
					<view class="card-icon-wrapper secondary">
						<text class="card-icon-large">📁</text>
					</view>
					<view class="card-info">
						<text class="card-title">音频管理</text>
						<text class="card-desc">上传和管理音频文件</text>
					</view>
					<text class="card-arrow">→</text>
				</view>
				
			</view>
		</view>


		<!-- 房间选择弹窗 - PC优化版 -->
		<el-dialog 
			title="选择房间"
			:visible.sync="roomSelectorVisible"
			width="480px"
			:show-close="true"
			:close-on-click-modal="true"
			:close-on-press-escape="true"
			custom-class="room-selector-dialog">
			
			<div class="room-list-container">
				<div class="room-option" 
					v-for="room in roomList" 
					:key="room.id"
					:class="{'option-active': room.id === currentRoom.id}"
					@click="selectRoom(room)">
					<div class="option-info">
						<div class="option-name">
							{{room.name}}
							<span v-if="room.password && room.password.trim() !== ''" class="password-lock">🔒</span>
						</div>
						<div class="option-desc">{{room.audioCount}}个音频</div>
					</div>
					<el-icon v-if="room.id === currentRoom.id" class="el-icon-check option-check"></el-icon>
				</div>
			</div>
			
			<div slot="footer" class="dialog-footer">
				<el-button @click="closeRoomSelector">关闭</el-button>
				<!-- <el-button type="primary" @click="addNewRoom">+ 新建房间</el-button> -->
			</div>
		</el-dialog>

	</view>
</template>

<script>
	export default {
		data() {
			return {
				// 直播状态
				isLive: false,
				
				// 当前房间
				currentRoom: {
					id: '1',
					name: '默认房间'
				},
				
				// 房间列表
				roomList: [],

				
				// 弹窗控制
				roomSelectorVisible: false
			}
		},
		onLoad() {
			this.initData();
		},
		methods: {
			// 初始化数据
			async initData() {
				// 加载房间数据
				try {
					await this.loadRooms();
					const savedRoom = uni.getStorageSync('currentRoom');
					if (savedRoom) {
						// 检查保存的房间是否还存在
						const existRoom = this.roomList.find(room => room.id === savedRoom.id);
						if (existRoom) {
							this.currentRoom = existRoom;
						} else {
							// 如果保存的房间不存在，选择第一个房间
							if (this.roomList.length > 0) {
								this.currentRoom = this.roomList[0];
							}
						}
					} else if (this.roomList.length > 0) {
						this.currentRoom = this.roomList[0];
					}
				} catch (e) {
					console.log('加载房间数据失败:', e);
				}
			},

			// 从API加载房间列表
			async loadRooms() {
				try {
					const response = await uni.request({
						url: 'http://localhost:8000/api/room/getRooms',
						method: 'GET'
					});
					
					console.log('API响应+++++:', response); // 调试信息
					
					if (response.data.code === 1) {
						this.roomList = response.data.data.map(room => ({
							id: room.id.toString(),
							name: room.name,
							audioCount: room.audio_count,
							password: room.has_password ? 'protected' : ''
						}));
						console.log('映射后的房间列表:', this.roomList); // 调试信息
					} else {
						console.error('加载房间失败:', response.data.msg);
					}
				} catch (error) {
					console.error('请求房间数据失败:', error);
					// 如果API请求失败，使用默认数据 
					this.roomList = [
						{ id: '1', name: '默认房间', audioCount: 0, password: '' }
					];
				}
			},

			// 显示房间选择器
			showRoomSelector() {
				console.log('显示房间选择器，当前房间列表:', this.roomList); // 调试信息
				this.roomSelectorVisible = true;
			},

			// 关闭房间选择器
			closeRoomSelector() {
				this.roomSelectorVisible = false;
			},

			// 选择房间
			async selectRoom(room) {
				// 如果选择的是当前房间，直接关闭弹窗
				if (room.id === this.currentRoom.id) {
					this.closeRoomSelector();
					return;
				}
				
				// 如果房间有密码，需要验证
				if (room.password && room.password.trim() !== '') {
					this.$prompt('该房间需要密码', `进入 ${room.name}`, {
						confirmButtonText: '确定',
						cancelButtonText: '取消',
						inputPlaceholder: '请输入房间密码',
						inputType: 'password',
						inputValidator: (value) => {
							if (!value || value.trim() === '') {
								return '密码不能为空';
							}
							return true;
						}
					}).then(async ({ value }) => {
						if (value && value.trim()) {
							// 调用API验证密码
							try {
								const response = await uni.request({
									url: 'http://localhost:8000/api/room/checkPassword',
									method: 'POST',
									data: {
										room_id: room.id,
										password: value.trim()
							}
						});
						
						if (response.data.code === 1) {
							this.switchToRoom(room);
						} else {
							this.$message({
								message: response.data.msg || '密码错误',
								type: 'error'
									});
								}
							} catch (error) {
								console.error('验证密码失败:', error);
								this.$message({
									message: '验证密码失败，请重试',
									type: 'error'
								});
							}
						}
					}).catch(() => {
						// 用户取消，不做任何操作
					});
				} else {
					// 没有密码，直接切换
					this.switchToRoom(room);
				}
			},
			
			// 切换到指定房间
			switchToRoom(room) {
				this.currentRoom = room;
				this.closeRoomSelector();
				
				// 保存选择的房间
				uni.setStorageSync('currentRoom', room);
				
				// 使用Element UI的Message组件
				this.$message({
					message: `已切换到 ${room.name}`,
					type: 'success',
					duration: 2000
				});
				
				// TODO: 加载该房间的播放配置
			},

			// 新建房间 - 使用Element UI的MessageBox
			addNewRoom() {
				this.closeRoomSelector();
				// 先输入房间名称
				this.$prompt('请输入房间名称', '新建房间', {
					confirmButtonText: '下一步',
					cancelButtonText: '取消',
					inputPlaceholder: '请输入房间名称',
					inputValidator: (value) => {
						if (!value || value.trim() === '') {
							return '房间名称不能为空';
						}
						return true;
					}
				}).then(({ value }) => {
					if (value && value.trim()) {
						const roomName = value.trim();
						// 再输入密码（可选）
						this.$prompt('设置房间密码（可选，不设置则直接确定）', '设置密码', {
							confirmButtonText: '创建房间',
							cancelButtonText: '返回',
							inputPlaceholder: '请输入房间密码（可选）',
							inputType: 'password'
						}).then(async ({ value: password }) => {
							// 调用API创建房间
							try {
								const response = await uni.request({
									url: 'http://localhost:8000/api/room/createRoom',
									method: 'POST',
									data: {
										name: roomName,
										password: password ? password.trim() : ''
									}
							});
							
							if (response.data.code === 1) {
								// 创建成功，重新加载房间列表
									await this.loadRooms();
									
									// 找到新创建的房间并切换到该房间
									const newRoom = this.roomList.find(room => room.name === roomName);
									if (newRoom) {
										this.switchToRoom(newRoom);
									}
									
									this.$message({
										message: '房间创建成功！',
										type: 'success'
									});
							} else {
								this.$message({
									message: response.data.msg || '创建房间失败',
									type: 'error'
									});
								}
							} catch (error) {
								console.error('创建房间失败:', error);
								this.$message({ 
									message: '创建房间失败，请重试',
									type: 'error'
								});
							}
						}).catch(() => {
							// 返回到房间名称输入
							this.addNewRoom();
						});
					}
				}).catch(() => {
					// 用户取消，不做任何操作
				});
			},

			// 配置播放列表
			configurePlaylist() {
				uni.navigateTo({
					url: `/pages/playlist/config?roomId=${this.currentRoom.id}`
				});
			},

			// 管理音频
			manageAudio() {
				uni.navigateTo({
					url: `/pages/audio/manage?roomId=${this.currentRoom.id}`
				});
			},



		},

			onUnload() {
				// 页面卸载时的清理工作
			}
	}
</script>

<style>
/* 容器和基础样式 */
.container {
	min-height: 92vh;
	background: linear-gradient(135deg, #f5f7fa 0%, #c3cfe2 100%);
	padding-bottom: 140rpx;
}

/* 房间头部 */
.room-header {
	background: #fff;
	padding: 24rpx 30rpx;
	display: flex;
	justify-content: space-between;
	align-items: center;
	box-shadow: 0 2rpx 20rpx rgba(0, 0, 0, 0.08);
	margin-bottom: 20rpx;
}

.room-info {
	flex: 1;
	display: flex;
	flex-direction: column;
	gap: 8rpx;
	min-width: 0; /* 防止flex子项溢出 */
}

.room-name {
	font-size: 38rpx;
	font-weight: 700;
	color: #2c3e50;
	white-space: nowrap;
	overflow: hidden;
	text-overflow: ellipsis;
	max-width: 450rpx;
}

.room-status {
	display: flex;
	align-items: center;
	gap: 8rpx;
	font-size: 26rpx;
	color: #7f8c8d;
}

.status-dot {
	width: 10rpx;
	height: 10rpx;
	border-radius: 50%;
	background: #e74c3c;
	flex-shrink: 0;
}

.status-live .status-dot {
	background: #27ae60;
	animation: pulse 2s infinite;
}

.status-text {
	white-space: nowrap;
}

@keyframes pulse {
	0%, 100% { opacity: 1; transform: scale(1); }
	50% { opacity: 0.7; transform: scale(1.1); }
}

.status-live {
	color: #27ae60 !important;
}

.room-switch-btn {
	display: flex;
	align-items: center;
	gap: 8rpx;
	padding: 18rpx 24rpx;
	background: linear-gradient(135deg, #6C7AE0, #9B59B6);
	color: #fff;
	border-radius: 32rpx;
	font-size: 28rpx;
	box-shadow: 0 4rpx 12rpx rgba(108, 122, 224, 0.3);
	flex-shrink: 0;
}

.room-switch-btn:active {
	transform: scale(0.95);
	transition: all 0.1s ease;
}

.switch-text {
	font-size: 28rpx;
	font-weight: 600;
}

.switch-icon {
	font-size: 22rpx;
	transition: transform 0.3s ease;
}

/* 功能操作区域 */
.function-section {
	background: #fff;
	margin: 0 20rpx 20rpx;
	border-radius: 20rpx;
	padding: 30rpx;
	box-shadow: 0 4rpx 20rpx rgba(0, 0, 0, 0.06);
}

.section-title {
	margin-bottom: 25rpx;
}

.title-text {
	font-size: 36rpx;
	font-weight: 700;
	color: #2c3e50;
	margin-bottom: 8rpx;
}

.title-desc {
	font-size: 26rpx;
	color: #7f8c8d;
}

.function-grid {
	display: flex;
	flex-direction: column;
	gap: 16rpx;
}

.function-card {
	display: flex;
	align-items: center;
	gap: 24rpx;
	padding: 32rpx;
	background: #f8f9fa;
	border-radius: 18rpx;
	border: 2rpx solid transparent;
	transition: all 0.2s ease;
}

.function-card:active {
	transform: translateY(2rpx);
	border-color: #6C7AE0;
	background: rgba(108, 122, 224, 0.05);
}

.card-icon-wrapper {
	width: 72rpx;
	height: 72rpx;
	border-radius: 14rpx;
	display: flex;
	align-items: center;
	justify-content: center;
	flex-shrink: 0;
}

.card-icon-wrapper.primary {
	background: linear-gradient(135deg, #6C7AE0, #9B59B6);
}

.card-icon-wrapper.secondary {
	background: linear-gradient(135deg, #27ae60, #2ecc71);
}


.card-icon-large {
	font-size: 32rpx;
	color: #fff;
}

.card-info {
	flex: 1;
	min-width: 0;
}

.card-title {
	font-size: 32rpx;
	font-weight: 600;
	color: #2c3e50;
	margin-bottom: 8rpx;
}

.card-desc {
	font-size: 26rpx;
	color: #7f8c8d;
}

.card-arrow {
	font-size: 28rpx;
	color: #bdc3c7;
	font-weight: 600;
	flex-shrink: 0;
}

/* Element UI Dialog 自定义样式 */
.room-selector-dialog {
	border-radius: 12px;
	overflow: hidden;
}

.room-selector-dialog .el-dialog__header {
	background: linear-gradient(135deg, #6C7AE0, #9B59B6);
	color: #fff;
	padding: 20px 24px;
}

.room-selector-dialog .el-dialog__title {
	color: #fff;
	font-size: 18px;
	font-weight: 600;
}

.room-selector-dialog .el-dialog__close {
	color: #fff !important;
	font-size: 20px;
}

.room-selector-dialog .el-dialog__body {
	padding: 0;
	max-height: 320px;
	overflow-y: auto;
}

.room-list-container {
	padding: 0;
}

.room-option {
	display: flex;
	justify-content: space-between;
	align-items: center;
	padding: 18px 24px;
	border-bottom: 1px solid #f5f7fa;
	cursor: pointer;
	transition: all 0.2s ease;
}

.room-option:last-child {
	border-bottom: none;
}

.room-option:hover {
	background: #f8f9fa;
}

.option-active {
	background: rgba(108, 122, 224, 0.08) !important;
	border-left: 3px solid #6C7AE0;
}

.option-active:hover {
	background: rgba(108, 122, 224, 0.12) !important;
}

.option-info {
	flex: 1;
	min-width: 0;
}

.option-name {
	font-size: 16px;
	color: #2c3e50;
	font-weight: 600;
	margin-bottom: 4px;
	white-space: nowrap;
	overflow: hidden;
	text-overflow: ellipsis;
}

.option-desc {
	font-size: 14px;
	color: #7f8c8d;
}

.password-lock {
	font-size: 12px;
	margin-left: 6px;
	opacity: 0.7;
	color: #f39c12;
}

.option-check {
	color: #6C7AE0;
	font-size: 18px;
	flex-shrink: 0;
}

.room-selector-dialog .el-dialog__footer {
	padding: 16px 24px;
	background: #f8f9fa;
	border-top: 1px solid #ecf0f1;
}

.dialog-footer {
	text-align: right;
}


/* PC端响应式设计 */
@media screen and (min-width: 768px) {
	.container {
		max-width: 800rpx;
		margin: 0 auto;
		padding: 0 40rpx 60rpx;
	}
	
	.room-header {
		padding: 30rpx 40rpx;
	}
	
	.function-section {
		margin: 0 0 24rpx;
	}
	
	/* PC端弹出层优化 */
	.room-selector-dialog {
		border-radius: 8px;
	}
	
	.room-selector-dialog .el-dialog {
		margin-top: 15vh !important;
	}
	
	.room-option {
		border-radius: 6px;
		margin: 4px 8px;
		padding: 16px 18px;
		border: 1px solid transparent;
	}
	
	.room-option:hover {
		background: #f5f7fa;
		border-color: #e4e7ed;
		transform: translateY(-1px);
		box-shadow: 0 2px 12px rgba(0, 0, 0, 0.1);
	}
	
	.option-active {
		background: rgba(108, 122, 224, 0.08) !important;
		border-color: #6C7AE0 !important;
		border-left: 3px solid #6C7AE0;
	}
	
	.option-active:hover {
		background: rgba(108, 122, 224, 0.12) !important;
	}
}
</style>
